package es.ceura.wilder.handlers;

import es.ceura.wilder.datastructures.response.HTTPCode;
import es.ceura.wilder.datastructures.response.HTTPResponse;
import es.ceura.wilder.datastructures.Header;
import es.ceura.wilder.datastructures.HeaderType;
import es.ceura.wilder.datastructures.response.ResponseStatusLine;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Set;

/**
 *
 * @author Jorge Madrid
 */
public class HTTPResponseSender {

    private Socket socket;
    private static final String NEW_LINE = "\r\n";
    private static final char SPACE = ' ';

    public HTTPResponseSender(Socket socket) {
        this.socket = socket;
    }

    public HTTPResponseSender() {
    }

    public void sendHTTPResponse(HTTPResponse response, Socket socket) throws IOException {
        OutputStream outputStream;
        DataOutputStream output;
        this.socket = socket;
        outputStream = socket.getOutputStream();

        output = new DataOutputStream(outputStream);

        writeStatusLine(response, output);

        writeHeaders(response, output);

        output.write(NEW_LINE.getBytes());

        output.write(response.getMessage());

        output.write(NEW_LINE.getBytes());
        output.write(NEW_LINE.getBytes());
    }

    private void writeStatusLine(HTTPResponse response, DataOutputStream output) throws IOException {
        ResponseStatusLine statusLine = response.getStatusLine();
        HTTPCode code = statusLine.getHTTPCode();

        output.write(statusLine.getHttpVersion().getBytes());
        output.write(SPACE);
        output.write(code.getName().getBytes());
        output.write(SPACE);
        output.write(code.getMessage().getBytes());
        output.write(NEW_LINE.getBytes());
    }

    private void writeHeaders(HTTPResponse response, DataOutputStream output) throws IOException {
        HashMap<HeaderType, Header> headers = response.getHeaderMap();
        Set<HeaderType> keys = headers.keySet();

        for (HeaderType headerType : keys) {
            output.write(headers.get(headerType).getValue().getBytes());
            output.write(':');
            output.write(SPACE);
            output.write(headers.get(headerType).getValue().getBytes());
            output.write(NEW_LINE.getBytes());
        }
    }

    public void sendHTTPResponse(HTTPResponse response) throws IOException {
        sendHTTPResponse(response, this.socket);
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }
}
